import axios from 'axios'
import qs from 'qs'

// eslint-disable-next-line no-unused-vars
import store from '@/store'
import { getToken, removeUserInfo } from '@/utils/auth'
import { isJSON } from '@/utils'

axios.defaults.transformRequest = (data, headers) => {
  if (getToken()) {
    headers.token = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  }

  if (headers['Content-Type'] === 'application/x-www-form-urlencoded' && data && Object.prototype.toString.call(data) === '[object Object]') {
    data = qs.stringify(data)
  }
  if (headers['Content-Type'] === 'application/json' && data && Object.prototype.toString.call(data) === '[object Object]') {
    data = JSON.stringify(data)
  }
  return data
}

const newAxios = axios.create({
  timeout: 15000
})

newAxios.interceptors.response.use(response => {
  const token = response.headers.token
  const res = isJSON(response.data) ? JSON.parse(response.data) : response.data
  if (token && res.data) {
    res.data.token = token
  }
  const { status } = res
  if (status == 403) {
    removeUserInfo()
    setTimeout(() => {
      window.location.href = '/login'
    }, 200)
  }

  return res
}, err => {
  return Promise.reject(err)
})

export function request(_param) {
  const {
    method = 'get',
    // `responseType` 表示服务器响应的数据类型，可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
    responseType = 'json', // 默认的
    headers = {},
    url = '',
    params,
    data,
    ...otherData
  } = _param

  if (!url) {
    return new Promise((resolve, reject) => {
      reject(new Error('url is null'))
    })
  }
  const _method = method.toLowerCase()

  if (_method === 'get') {
    return newAxios({
      responseType,
      url,
      headers,
      method,
      params: params || data || otherData
    })
  }

  if (_method === 'post' || _method === 'delete' || _method === 'put' || _method === 'patch') {
    if (!Object.prototype.hasOwnProperty.call(headers, 'Content-Type')) {
      headers['Content-Type'] = 'application/json'
    }

    return newAxios({
      responseType,
      url,
      headers,
      method,
      data
    })
  }
}

export default newAxios
